package logging.system;

import java.io.*;
import java.util.*;

public class LogManager {
    // 日志文件路径
    private String logTxtPath = "D:\\log.txt";
    // 构造函数
    public LogManager() {
        try {
            File logFile = new File(logTxtPath);
            if (!logFile.exists()) {
                boolean created = logFile.createNewFile();
                if (created) {
                    System.out.println("✅ 日志文件已创建: " + logTxtPath);
                } else {
                    System.err.println("❌ 无法创建日志文件");
                }
            } else {
                System.out.println("📄 日志文件已存在: " + logTxtPath);
            }
        } catch (IOException e) {
            System.err.println("❌ 创建日志文件时出错: " + e.getMessage());
        }
    }

    /**
     * 写入日志的方法，传入用户名和 SQL 语句。
     * @param username 用户名
     * @param sql SQL 语句
     */
    public void writeLog(String username, String sql) {
        File logFile = new File(logTxtPath);
        BufferedReader reader = null;
        BufferedWriter writer = null;
        StringBuilder fileContent = new StringBuilder();
        boolean userFound = false;

        try {
            // 读取现有日志内容
            reader = new BufferedReader(new FileReader(logFile));
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent.append(line).append("\n");

                // 检查当前行是否包含该用户名
                if (line.startsWith(username + ",")) {
                    userFound = true;
                }
            }

            // 如果找到对应用户名，更新该用户日志，若未找到则追加
            if (userFound) {
                // 将新的 SQL 语句添加到现有用户的日志末尾
                String updatedContent = fileContent.toString().replaceFirst(username + ",.*", username + "," + sql);
                writer = new BufferedWriter(new FileWriter(logFile));
                writer.write(updatedContent);
            } else {
                // 如果没有找到用户名，直接将新的记录写入文件末尾
                writer = new BufferedWriter(new FileWriter(logFile, true));
                writer.write(username + "," + sql + "\n");
            }

            System.out.println("✅ 日志写入成功");
        } catch (IOException e) {
            System.err.println("❌ 写入日志时出错: " + e.getMessage());
        } finally {
            try {
                if (reader != null) reader.close();
                if (writer != null) writer.close();
            } catch (IOException e) {
                System.err.println("❌ 关闭文件流时出错: " + e.getMessage());
            }
        }
    }

    /**
     * 获取所有日志记录，每行返回一个字符串。
     * @return 包含所有日志记录的 List<String>
     */
    public List<String> getAllLogs() {
        List<String> logs = new ArrayList<>();
        File logFile = new File(logTxtPath);
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(logFile));
            String line;
            while ((line = reader.readLine()) != null) {
                logs.add(line);
            }
        } catch (IOException e) {
            System.err.println("❌ 读取日志时出错: " + e.getMessage());
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                System.err.println("❌ 关闭文件流时出错: " + e.getMessage());
            }
        }
        return logs;
    }

    /**
     * 获取指定用户的所有日志记录
     * @param username 用户名
     * @return 包含指定用户日志记录的 List<String>
     */
    public List<String> getUserLogs(String username) {
        List<String> userLogs = new ArrayList<>();
        File logFile = new File(logTxtPath);
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(logFile));
            String line;
            while ((line = reader.readLine()) != null) {
                // 仅添加该用户的日志记录
                if (line.startsWith(username + ",")) {
                    userLogs.add(line);
                }
            }
        } catch (IOException e) {
            System.err.println("❌ 读取日志时出错: " + e.getMessage());
        } finally {
            try {
                if (reader != null) reader.close();
            } catch (IOException e) {
                System.err.println("❌ 关闭文件流时出错: " + e.getMessage());
            }
        }
        return userLogs;
    }
}
